// index.js
import {
  get,
  post
} from '../../utils/request'
import {
  APIS
} from '../../utils/api'
import {
  timestampToTime
} from '../../utils/util'


// 获取应用实例
const app = getApp()

Page({
  data: {
    currentIndex: 0,
    currentShopIndex: 0,
    shopArray: [],
    shopIds: [],
    shopList: [],
    enumArray: [],
    enum: [],
    type: '',
    action: 'new',
    startDate: '-',
    endDate: '-',
    rangeStart: '1990-01-01',
    rangeEnd: '1990-01-01',
    efficient: 2,
    mainuse: ['否', '是'],
    mainuseIdx: 0,
    loading: false,
    name: '',
    amount: '',
    presentation: '',
    id: undefined,
    deposit: 0
  },
  async onLoad(options) {
    this.getShopData();
    if (options.type === 'discount') {
      await this.getEnumData();
    }
    const temp = new Date().getTime();
    const startDate = timestampToTime(temp);
    const endDate = timestampToTime(temp + 24 * 60 * 60 * 1000);
    const rangeEnd = timestampToTime(temp + 365 * 24 * 60 * 60 * 1000);
    if (options.action === 'modify') {
      this.getDetail(options)
    }
    else {
      this.setData({
        startDate,
        endDate
      })
    }
    this.setData({
      show: true,
      rangeEnd,
      type: options.type,
      action: options.action
    })
  },
  getShopData() {
    const shopList = wx.getStorageSync('shopList');
    const shopArray = shopList.map(x => x.name);
    const shopIds = shopList.map(x => x.id);
    this.setData({
      shopList,
      shopArray,
      shopIds,
    });
  },
  getEnumData() {
    get(APIS.enum).then(res => {
      const list = res.data;
      if (!list.length) {
        return []
      }
      const enumArray = list.map(x => x.name);
      this.setData({
        enumArray,
        enum: list
      });
    })
  },
  bindChangeEnum(e) {
    const currentIndex = e.detail.value;
    this.setData({
      currentIndex: +currentIndex
    });
  },
  handleStart(e) {
    let date = e.detail.value;
    let endDate = new Date(date) < new Date(this.data.endDate) ?
      this.data.endDate :
      date
    this.setData({
      startDate: date,
      endDate,
    }, () => {
      this.calcData();
    });
  },
  handleEnd(e) {
    const endDate = e.detail.value;
    this.setData({
      endDate
    }, () => {
      this.calcData();
    });
  },
  calcData() {
    let {
      startDate,
      endDate
    } = this.data;
    // 将字符串日期转换为Date对象  
    const date1 = new Date(startDate);
    const date2 = new Date(endDate);

    // 计算两个日期之间的差值（毫秒）  
    const diffTime = Math.abs(date2.getTime() - date1.getTime());

    // 将毫秒转换为天  
    const diffDays = Math.ceil(diffTime / (1000 * 3600 * 24)) + 1;
    this.setData({
      efficient: diffDays
    })
  },
  handleEfficientBlur() {
    console.log(this.data.efficient)
    if (!this.data.efficient || this.data.efficient < 0) {
      this.calcData();
    }
  },
  handleEfficient(e) {
    let {
      startDate
    } = this.data;
    let input = e.detail.value;
    if (input <= 0 || !input) {
      return;
    }
    // 10 不用管，算是误差吧
    let endDate = (+new Date(startDate)) + ((input - 1) * 24 * 3600 * 1000) + 10;
    console.log(endDate, startDate)
    let nEnd = new Date(endDate);
    let year = String(nEnd.getFullYear()).padStart(2, '0');
    let month = String(nEnd.getMonth() + 1).padStart(2, '0');
    let day = String(nEnd.getDate()).padStart(2, '0')
    this.setData({
      efficient: input,
      endDate: `${year}-${month}-${day}`
    })
  },
  bindChangeShop(e) {
    const currentShopIndex = e.detail.value;
    console.log(currentShopIndex)
    this.setData({
      currentShopIndex: +currentShopIndex
    });
  },
  bindChangeMain(e) {
    console.log(e)
    const mainuseIdx = e.detail.value;
    this.setData({
      mainuseIdx
    });
  },
  bindChangeDeposit(e) {
    console.log(e)
    const deposit = e.detail.value;
    this.setData({
      deposit
    });
  },

  formSubmit(e) {
    const type = this.data.type;
    const params = e.detail.value;
    const {eid, name, duration, efficient, number, shop, amount, presentation} = params;
    if (
      type === 'discount' &&
      !(name && efficient && number &&
        ((amount && eid === 0) || (duration && eid === 1))
      )
    ) {
      wx.showToast({
        title: '缺少必填项',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    else if (
      type === 'recharge' && 
      !(name && amount && presentation && efficient)
    ) {
      wx.showToast({
        title: '缺少必填项',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    if (this.data.loading) {
      return;
    }
    this.setData({
      loading: true
    })
    const {shopList, enumArray, action, id} = this.data;
    let sShop = shopList[shop]
    post(`${type === 'recharge' ? APIS.recharge : APIS.discount}`, {
      ...params,
      sname: sShop.name,
      shop: sShop.id,
      alias: type === 'recharge' ? undefined : enumArray[eid],
      action,
      id: id
    }).then(res => {
      this.setData({
        loading: false
      })
      wx.showToast({
        icon: 'none',
        title: res.message,
      })
      wx.navigateBack(-1)
    })
  },

  getDetail(options) {
    const { type, id, action } = options;
    const baseUrl = type === 'recharge'
      ? `${APIS.recharge}/${id}`
      : `${APIS.discount}/${id}`;
    this.setData({
      type,
      action
    })
    get(baseUrl).then(res => {
      let {data} = res.data;
      let ndata = {...data};
      delete ndata.shop;
      delete ndata.updatedAt;
      delete ndata.createdAt;
      delete ndata.mainuse;
      delete ndata.remain;

      this.setData({
        startDate: data.start,
        endDate: data.end,
        currentShopIndex: this.data.shopList.findIndex(v => +v.id === +data.shop),
        currentIndex: data.eid ? undefined : +data.eid,
        mainuseIdx: data.mainuse,
        ...ndata
      })
    })
  }
})